package Stock;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.text.*;

public class Stock {

	private String m_StockName;
	private StockStatus m_Status;
	private Date m_StartDate;
	private int m_Amount;
	private float m_StartValue;
	private List<Transaction> m_Transactions;
	private List<Float> m_ATR;
	

	public StockStatus getStatus() {
		return m_Status;
	}
	
	public Date getLastDate()
	{
		return m_Transactions.get(m_Transactions.size()-1).getStockDate();
	}

	public int getAmount() {
		return m_Amount;
	}

	public Date getStartDate() {
		return m_StartDate;
	}

	public void setStatus(StockStatus value) throws Exception {
		m_Status = value;
	}

	public float getStartValue() {
		return m_StartValue;
	}
	
	public List<Float> getATR() {
		if(null == m_ATR || m_ATR.size() != m_Transactions.size())
			calculateATR( );
		
		return m_ATR;
	}
 
	public List<Transaction> getStockTransactions() {
		Collections.sort(m_Transactions, new SortTransaction());
		System.out.println("SORTING");
		return m_Transactions;
	}

	public String getStockName() {
		return m_StockName;
	}
	
	private void calculateATR() 
	{
		List<Transaction> totals=new ArrayList<Transaction>(m_Transactions);
		m_ATR = ATR.getATRFromTransactions(totals);
	}

	public Stock(String stockName, String path) {

		m_StockName = stockName;
		m_Transactions = new ArrayList<Transaction>();
 
		loadStock(path);
	}

	public Stock(String stockName, List<Transaction> stocks,StockStatus status, float startValue, Date startDate)
			throws Exception {
		// TODO validators amount & startdate
		this(stockName, stocks, status, startValue, startDate, 1);
	}

	public Stock(String stockName, List<Transaction> stocks,
			StockStatus status, float startValue, Date startDate, int amount)
			throws Exception {
		if (validProperties(stockName, startValue, startDate, amount)) {
			this.m_StockName = stockName;
			this.m_StartValue = startValue;
			this.m_Status = status;
			this.m_StartDate = startDate;
			this.m_Amount = amount;
			fillStockChanges(stocks);
		} else {
			throw new Exception("Not a valid stock");
		}
	}

	private void fillStockChanges(List<Transaction> stocks) {
		m_Transactions = stocks;
	}

	public void addStockChange(Transaction stock) {
		m_Transactions.add(stock);

	}

	public void loadStats(String line) {
		for (int i = 0; i < 4; i++) {
			line = ParseStats(line, i);
		}
	}

	public String ParseStats(String line, int run) {
		int seperator = line.indexOf(",");

		switch (run) {
		case 0:
			DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			try {
				m_StartDate = (Date) formatter.parse(line.substring(0,
						seperator - 1));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case 1:
			m_Amount = Integer.parseInt(line.substring(0, seperator));
			break;
		case 2:
			m_StartValue = Integer.parseInt(line.substring(0, seperator));
			break;
		case 3:
			// StockStatus.valueOf(line.substring(0, seperator-1));
			m_Status = StockStatus.Open;
			break;
		default:
			break;
		}

		return line.substring(seperator + 1, line.length());
	}

	public void loadStock(String FilePath) {
		try {
			
			FileReader input = new FileReader(FilePath);
			BufferedReader reader = new BufferedReader(input);

			m_Transactions.clear();
			readTransaction(reader);
			input.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void readTransaction(BufferedReader reader) throws NumberFormatException, IOException {
		String line = reader.readLine();
		loadStats(line);
		line = reader.readLine();

		while ((line = reader.readLine()) != null) {
			try {
				int seperator = line.indexOf(",");
				DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
				String temp = line.substring(0, seperator);
				Date date = (Date) formatter.parse(temp);
				line = line.substring(seperator + 1, line.length());

				seperator = line.indexOf(",");
				float open = Float.parseFloat(line.substring(0, seperator));
				line = line.substring(seperator + 1, line.length());

				seperator = line.indexOf(",");
				float high = Float.parseFloat(line.substring(0, seperator));
				line = line.substring(seperator + 1, line.length());

				seperator = line.indexOf(",");
				float low = Float.parseFloat(line.substring(0, seperator));
				line = line.substring(seperator + 1, line.length());

				seperator = line.indexOf(",");
				float close = Float.parseFloat(line.substring(0, seperator));
				line = line.substring(seperator + 1, line.length());

				seperator = line.indexOf(",");
				line = line.substring(seperator + 1, line.length());

				seperator = line.indexOf(",");
				float adjclose = Float.parseFloat(line);

				Transaction stock = new Transaction(open, high, low, close,
						adjclose, date);

				m_Transactions.add(stock);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
		}
	}

	public void saveStock() {
		try {
			// TODO controleren of dit bestand al bestaat
			FileWriter writer = new FileWriter("./Stock/" + m_StockName
					+ ".txt");
			String output = m_StartDate.toString() + m_StartValue + m_Amount
					+ m_Status.toString() + "\n";
			output += "Date,Open,High,Low,Close,Volume,Adj Close\n";
			output += getTransactions();
			writer.write(output);
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private String getTransactions() {
		String transactions = "";
		for (Transaction transaction : m_Transactions) {
			transactions += transaction.getStockDate().toString() + ",";
			transactions += transaction.getOpen() + ",";
			transactions += "0,0,";
			transactions += transaction.getClose() + ",";
			transactions += "0,";
			transactions += transaction.getAdjustmentClose() + "\n";
		}
		return transactions;
	}

	public float getCurrentValue() {
		System.out
				.println("getCurrentValue (stockValues)STILL NEEDS TO BE DONE!!!!");
		return 0;
	}

	public float CurrentValue() {
		return m_Transactions.get(m_Transactions.size()).getAdjustmentClose();
	}

	// VALIDATORS
	public boolean validProperties(String stockName, float startValue,
			Date startDate, int amount) {
		return (validStockname(stockName) && validstartValue(startValue) && validAmount(amount));
	}

	private boolean validAmount(int amount) {
		return amount > 0;
	}

	private boolean validstartValue(float startValue) {
		return startValue > 0;
	}

	private boolean validStockname(String stockName) {
		return !stockName.trim().equals("");
	}
	
	

}
